<?php
// https://paas.huifu.com/partners/api#/smzf/api_jhzs?id=h5wx
namespace jy_huifuapi;
defined('BY_JYA') or exit('error');
class pay extends \plugin{
    public function __construct($setting=array()){
        parent::__construct('jy_huifuapi');
        $setting=uni_setting('pay');
        if(!$setting['huifuapi_sysid'] || !$setting['huifuapi_productid'] || !$setting['huifuapi_private'] || !$setting['huifuapi_public']){
            exi('商户sysid，商户productid，商户私钥，汇付公钥，都必须填写','error');
        }
		$wechat=pdo_get('core_account_wechat',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1));
        if(!$wechat['id']){
            $wechat=pdo_get('core_account_wechat',array('uniacid'=>$_SESSION['uniacid']));
		}
		//没有添加公众号，也能访问，调用系统公众号
		if((empty($wechat) || ($wechat['is_auth']==1 && empty($wechat['appid']))) && $_SESSION['auth_wxid']){
			$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['auth_wxid']));
		}
        $wechat_appid=$wechat['appid'];
		if($_SESSION['wxapp_id'] && !$_SESSION['fromh5wxapp']){
			$wxapp=pdo_get('core_account_wxapp',array('uniacid'=>$_SESSION['uniacid'],'id'=>$_SESSION['wxapp_id']));
			$wxapp_appid=$wxapp['appid'];
		}
        $this->config=array(
            'sub_appid'=>$wxapp_appid?:$wechat_appid,
			'alipay_store_id'=>$alipay_store_id,
            'sys_id'=>$setting['huifuapi_sysid'],
            'product_id'=>$setting['huifuapi_productid'],
			'huifuapi_private'=>$setting['huifuapi_private'],
        );
    }
    //支付
    public function create($pay_log,$paytype=''){
		$log=model('jy_huifuapi/model')->checklog($pay_log['tid']?:$pay_log['ordersn'],1);
		if($log['id'] && $log['res']['pay_info']){
			$pay_info=json_decode($log['res']['pay_info'],true);
			return $pay_info;
		}
        if($paytype=='wechat'){
			$trade_type='T_JSAPI';
		}elseif($paytype=='wxapp'){
			$trade_type='T_MINIAPP';
		}elseif($paytype=='alipay'){
			$trade_type='A_JSAPI';
		}
		$time_expire=TIMESTAMP+9000;
		$biz_content = array(
				"req_date" => date('Ymd', TIMESTAMP),
				"req_seq_id" =>$pay_log['tid']?:$pay_log['ordersn'],
				"huifu_id" =>$this->config['sys_id'],
				"goods_desc" => $pay_log['title'],
				"trade_type" => $trade_type,
				"trans_amt" => $pay_log['fee'],
				"time_expire" => date('YmdHis', $time_expire),
				"notify_url" => $pay_log['notify_url']?custom_url($pay_log['notify_url'],true):SITEROOT .'addons/jy_huifuapi/notify.php',
		);
		if($paytype=='wechat' || $paytype=='wxapp'){
			$wx_data=array(
				'sub_appid'=>$this->config['sub_appid'],
				'openid'=>$pay_log['openid']?:$_SESSION['openid'],
			);
			$biz_content['wx_data']=ijson_encode($wx_data);
		}elseif($paytype=='alipay'){
			$alipay_data=array(
				'buyer_id'=>$pay_log['openid']?:$_SESSION['openid'],
			);
			$biz_content['alipay_data']=ijson_encode($alipay_data);
		}
        file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 支付记录:" .ijson_encode($biz_content)."\r\n", FILE_APPEND);
        $res=$this->request('https://api.huifu.com/v2/trade/payment/jspay',$biz_content);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 返回信息:" . ijson_encode($res)."\r\n", FILE_APPEND);
		if($res['resp_code']!='00000000' && $res['resp_code']!='00000100'){
			exi('支付失败，失败原因:'.$res['resp_code'].$res['resp_desc'],'error');
		}
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " pay_info:" . $res['pay_info']."\r\n", FILE_APPEND);
		$payment=json_decode($res['pay_info'],true);
		model('jy_huifuapi/model')->uplog($res,$biz_content['req_seq_id'],1);
		if($paytype=='wechat' || $paytype=='wxapp'){
			exi($payment);
		}elseif($paytype=='alipay'){
			exi($payment);
		}
		exi($payment);
    }
	//退款
    public function refund_pay($refund,$paytype=''){
		$log=model('jy_huifuapi/model')->checklog($refund['tid']?:$refund['ordersn'],4);
		if($log['id']){
			exi('该订单已申请过退款！','error');
		}
		$payinfo=pdo_get('core_paylog',array('uniacid'=>$_SESSION['uniacid'],'tid'=>$refund['tid']));
		$refund['paytime']=$payinfo['paytime']?:$payinfo['createtime'];
        if($paytype=='wechat'){
			$trade_type='T_JSAPI';
		}elseif($paytype=='wxapp'){
			$trade_type='T_MINIAPP';
		}elseif($paytype=='alipay'){
			$trade_type='A_JSAPI';
		}
		$biz_content = array(
				"req_date" => date('Ymd', TIMESTAMP),
				"req_seq_id" =>$refund['tid']?:$refund['ordersn'],
				"org_req_date" => date('Ymd', $refund['paytime']),
				"huifu_id" =>$this->config['sys_id'],
				"org_party_order_id" => $refund['transid'],
				"ord_amt" => $refund['money'],
				"notify_url" => SITEROOT .'addons/jy_huifuapi/notify.php',
		);
		if($paytype=='wechat' || $paytype=='wxapp'){
		}elseif($paytype=='alipay'){
		}
        //file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 支付记录:" .$biz_content_json."\r\n", FILE_APPEND);
        $res=$this->request('https://api.huifu.com/v2/trade/payment/scanpay/refund',$biz_content);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 返回信息:" . ijson_encode($res)."\r\n", FILE_APPEND);
		if($res['resp_code']!='00000000' && $res['resp_code']!='00000100'){
			exi('支付失败，失败原因:'.$res['resp_code'].$res['resp_desc'],'error');
		}
		model('jy_huifuapi/model')->uplog($res,$biz_content['req_seq_id'],4);
		$res['refund_id']=$res['hf_seq_id'];
		return $res;
    }
	public function request($url,$post=null,$continue=true,$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$sign=$this->getSign($post);
		$apipost=array(
			'sys_id'=>$this->config['sys_id'],
			'product_id'=>$this->config['product_id'],
			'data'=>$post,
			'sign'=>$sign,
		);
		$post=ijson_encode($apipost);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . $url." request记录:" . $post."\r\n", FILE_APPEND);
		$rurl=$url;
		if($isjson){
			$headers = array('Content-Type' => 'application/json');
			$result=cfc('http')->ihttp_json($rurl,$post);
		}elseif($isrequest){
			$result=cfc('http')->ihttp_request($rurl,$post);
		}elseif($post){
			$result=cfc('http')->ihttp_json($rurl,$post);
		}else{
			$result=cfc('http')->ihttp_get($rurl);
		}
		if(is_error($result)){			
			$message="支付错误, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		//print_r($result);exit;
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if($data['errcode']){
			$message=$this->error_code($data['errcode']).' '.$data['errmsg'].' '.$data['errcode'];
			if($return_error || $_SESSION['this']=='custom'){
				//return error($message);
			}else{
				//exi($message,'error');
			}
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
		    $message='支付错误，以下为原始数据：'.$result['content'];
    		if($return_error){
    			return error($message);
    		}else{
    			exi($message,'error');
    		}
		}
		$data=$data['data'];
		return $data;
	}
   /**
		 * 私钥加签（对数据源排序），可用于 V2 版本接口数据加签
		 *
		 * @param array $data 原数据( 排序后的json字符串; 数组参数排序后转json字符串(数据的中文和斜杠均不转码): 
									ksort($post_data); json_encode($post_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); )
		 *
		 * @param string $rsaPrivateKey 私钥
		 * @param int $alg 默认 OPENSSL_ALGO_SHA256
		 *
		 * @return string 签名串
	*/
    public function getSign($post_data=array(), $alg=OPENSSL_ALGO_SHA256){
		ksort($post_data); 
		$data=json_encode($post_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 签名串:" .$data."\r\n", FILE_APPEND);
		$rsaPrivateKey=$this->config['huifuapi_private'];
		$key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($rsaPrivateKey, 64, "\n", true)."\n-----END PRIVATE KEY-----";
		$signature= '';
		try {
			openssl_sign($data, $signature, $key, $alg);
		} catch (\Exception $e) {
			echo $e->getMessage();
		}
		return base64_encode($signature);
    }
	public function encrypt_data($biz_content_json='') {
		//分段加密方法
		$publicKey = $this->config['heepay_public'];
		// 要加密的数据
		$data = $biz_content_json;
		// 定义每个分段的大小
		$chunkSize = 117; // 2048-bit key can encrypt 117 bytes
		// 分段加密
		$encryptedData = '';
		for ($i = 0; $i < strlen($data); $i += $chunkSize) {
			$chunk = substr($data, $i, $chunkSize);
			openssl_public_encrypt($chunk, $encryptedChunk, $publicKey);
			$encryptedData .= $encryptedChunk;
		}
		// 将分段加密后的数据进行处理（例如Base64编码）并发送给接收方
		$encrypt_data = base64_encode($encryptedData);
		return $encrypt_data;
	}
	public function getdata($data1='') {
		$private_key_str=$this->config['huifuapi_private'];
		$encryptedData = base64_decode($data1);
		// 定义每个分段的大小
		$chunkSize = 256; // 2048-bit key can decrypt 256 bytes
		$PRIVATEkey=$private_key_str;
		// 分段解密
		$decryptedData = '';
		for ($i = 0; $i < strlen($encryptedData); $i += $chunkSize) {
			$chunk = substr($encryptedData, $i, $chunkSize);
			openssl_private_decrypt($chunk, $decryptedChunk, $PRIVATEkey);
			$decryptedData .= $decryptedChunk;
		}
		return $decryptedData;
	}
	public function upsms($pay_log=array(),$hy_token_id=''){
		$pay_log['mid']=$pay_log['mid']?:$_SESSION['uid'];
		$sn=$pay_log['tid']?:$pay_log['ordersn'];
		$sms=pdo_get('jy_huifuapi_smslog',array('sn'=>$sn,'uniacid'=>$_SESSION['uniacid'],"mid"=>$pay_log['mid']));
		if($sms['id']){
			pdo_update('jy_huifuapi_smslog',array('hy_token_id'=>$hy_token_id),array('sn'=>$pay_log['tid'],'uniacid'=>$_SESSION['uniacid'],"mid"=>$pay_log['mid']));
			return $sms;
		}
		$sms=array(
			'uniacid'=>$_SESSION['uniacid'],
			"mid"=>$pay_log['mid'],
			"sn" => $pay_log['tid'],
			'hy_token_id'=>$hy_token_id,
			"createtime" => TIMESTAMP,
		);
		pdo_insert('jy_huifuapi_smslog',$sms);
		$sms['id']=pdo_insertid();
		return $sms;
	}
}